package com.momomian.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author momomian
 * @date 2021/12/30
 */
@Slf4j
public class ObjectUtil {

    /**
     * 判断对象中属性值是否全为空
     */
    public static boolean allFieldsIsNull(Object object) {
        if (null == object) {
            return true;
        }
        try {
            for (Field f : object.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                if (f.get(object) != null && StringUtils.isNotBlank(f.get(object).toString())) {
                    return false;
                }
            }
        } catch (Exception e) {
            log.error("[ObjectUtil] error:", e);
        }
        return true;
    }


    /**
     * 根据属性，获取get方法
     *
     * @param object 对象
     * @param name   属性名
     */
    public static Object getFieldValue(Object object, String name) {
        try {
            PropertyDescriptor pd = new PropertyDescriptor(name, object.getClass());
            Method rM = pd.getReadMethod();
            return rM.invoke(object);
        } catch (IllegalAccessException | InvocationTargetException | IntrospectionException e) {
            e.printStackTrace();
        }
        return null;
    }
}
